import socket
import threading


class Server:
    __instance = None

    def __init__(self):
        """创建套接字让他进行连接"""
        self.server = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
        self.server.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, True)
        self.server.bind(('', 6789))
        self.server.listen(20)

    def run(self):
        while True:
            sock_user, address = self.server.accept()
            print(address)
            threading.Thread(target=self.msg, args=(sock_user,)).start()

    def msg(self, sock):
        """用于和他进行信息保持"""
        try:
            while True:
                user_msg = sock.recv(1024).decode('utf-8')
                print(user_msg)
        except Exception as Error:
            print('用户退出---', Error)
            sock.close()

    def send_msg(self, sock, msg):
        """给使用者返回信息"""
        sock.send(msg.encode('utf-8'))

    def __new__(cls, *args, **kwargs):
        """只存在一台服务器"""
        if not cls.__instance:
            cls.__instance = super().__new__(cls, *args, **kwargs)
            return cls.__instance


if __name__ == '__main__':
    server = Server()
    server.run()
